<?php
// +----------------------------------------------------------------------
// | 应用公共文件
// +----------------------------------------------------------------------
/*
 * 检测浏览器
 * **/
function is_mobile()
{
    // returns true if one of the specified mobile browsers is detected
    $regex_match="/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";
    $regex_match.="htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|";
    $regex_match.="blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";
    $regex_match.="symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";
    $regex_match.="jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";
    $regex_match.=")/i";
    return isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']) or preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT']));
}

/**
 * 邮件发送函数
 */
//function sendMail($to, $name$subject, $content,$fromName) {//$to为收件人数组
function sendMail($sendto_email, $subject, $body, $user_name)
{//$to为收件人数组
    $mail = new PHPMailer();
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host=config('mail.mail_host'); //smtp服务器的名称（这里以qq邮箱为例）
    $mail->SMTPAuth = config('mail.mail_smtpauth'); //启用smtp认证
    $mail->Username = config('mail.mail_username'); //你的邮箱名
    $mail->Password = config('mail.mail_password') ; //邮箱密码
    $mail->From = config('mail.mail_from'); //发件人地址（也就是你的邮箱地址）
    $mail->FromName = config('mail.mail_fromname'); //发件人姓名
    $mail->AddAddress($sendto_email,$user_name);
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML(config('mail.mail_ishtml')); // 是否HTML格式邮件
    $mail->CharSet=config('mail.mail_charset'); //设置邮件编码
    $mail->Subject =$subject; //邮件主题
    $mail->Body = $body; //邮件内容
    $mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //邮件正文不支持HTML的备用显示
    if(!$mail->Send()) {
        $msg = ['rel'=>0,'msg'=>$mail->ErrorInfo];
    } else {
        $msg = ['rel'=>1,'msg'=>'发送成功'];
    }
    return $msg;
}

//微信登陆
function wuserinfo($appid,$appsecret,$url)
{
    $code = input('get.code');
    if(empty($code)){
        $url = urlencode($url);
        header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$url&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        exit();
    }
    $curllink = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
    $jsoninfo = curl($curllink,'',1);
    $access_token = $jsoninfo['access_token'];
    $openid = $jsoninfo['openid'];
    $link = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
    $userinf = curl($link,'',1);
    return $userinf;

}

function curl($curllink,$data = null,$type = 0)
{
    //初始化一个curl对象
    $ch = curl_init($curllink);
    //设置需要抓取的url
    curl_setopt($ch, CURLOPT_URL, $curllink);
    //跳过SSL证书检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设定是否显示头信息
    $output = curl_exec($ch);//执行
    curl_close($ch);//关闭
    if ($type==0){
        $jsoninfo = json_decode($output);//解析json格式为对象
    }else{
        $jsoninfo = json_decode($output, true);//解析json格式为数组
    }

    return $jsoninfo;
}


function Post($curlPost,$url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    $return_str = curl_exec($curl);
    curl_close($curl);
    return $return_str;
}

//xml转array
function xml_to_array($xml)
{
    $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
    if(preg_match_all($reg, $xml, $matches)){
        $count = count($matches[0]);
        for($i = 0; $i < $count; $i++){
            $subxml= $matches[2][$i];
            $key = $matches[1][$i];
            if(preg_match( $reg, $subxml )){
                $arr[$key] = xml_to_array( $subxml );
            }else{
                $arr[$key] = $subxml;
            }
        }
    }
    return $arr;
}

//生成6位随机数
function random($length = 6 , $numeric = 0)
{
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    if($numeric){
        $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
    }else{
        $hash = '';
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
    }
    return $hash;
}

//模板消息
function sendmsg($openid,$appid,$appsecret,$data){

    $actoken = getAccessToken($appid,$appsecret);
    $temurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$actoken";
    $rel = curl($temurl,$data);
}

//获取AccessToken
function getAccessToken($appid,$appsecret) {
    // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
    $data = unserialize(file_get_contents("../public/access_token.json"));
    //return $data->expire_time;
    if ($data['expire_time'] < time()) {
        // 如果是企业号用以下URL获取access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";

        $res = curl($url,'',1);
        $access_token = $res['access_token'];
        if ($access_token) {
            $data['expire_time'] = time() + 7000;
            $data['access_token'] = $access_token;
            $fp = fopen("../public/access_token.json", "w+");
            $jsondata = serialize($data);
            fwrite($fp, $jsondata);
            fclose($fp);
        }
    } else {
        $access_token = $data['access_token'];
    }
    return $access_token;
}

function smtp_mail( $sendto_email, $subject, $body, $user_name)
{
    Vendor('PHPMailer.PHPMailerAutoload');
    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以qq邮箱为例）
    $mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
    $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
    $mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
    $mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
    $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
    $mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
    $mail->Encoding = "base64";
    $mail->AddAddress($sendto_email,$user_name);  // 收件人邮箱和姓名
    $mail->WordWrap = 50; // set word wrap 换行字数
    // 邮件主题
    $mail->Subject = $subject;
    // 邮件内容
    $mail->Body = '
        <html><head><meta http-equiv=\"Content-Language\" content=\"zh-cn\">
        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head>   
        <body>'.$body.'</body></html>';
    $mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //邮件正文不支持HTML的备用显示
    if(!$mail->Send()) {
        $msg = array('code'=>0,'msg'=>$mail->ErrorInfo);
    } else {
        $msg = array('code'=>1,'msg'=>'发送成功');
    }
    return $msg;
}